package com.inter.aspect;

import com.inter.my.ClassYinXing;
import com.inter.vo.Response;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * @author yinxing
 * @date 2022-09-15
 */
@Slf4j
@Aspect
@Configuration
public class ClassAspect {

    @Around("@within(classYinXing)")
    public Object around(ProceedingJoinPoint joinPoint,ClassYinXing classYinXing) throws Throwable {
        log.info("进来了");
        //获取ip，IpUtils这是获取ip的工具类，自己在网上百度，或者看我以前作品都有
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        if (classYinXing.auth()) {
            String auth = request.getHeader("yx-auth");
            if (StringUtils.isEmpty(auth)){
                return Response.builder().code(205).message("没权限！").build();
            }
        }
        Cookie[] cookies = request.getCookies();
        StringBuffer cookieString = new StringBuffer("cookie:");
        if (cookies.length>0){
            Stream<Cookie> limit = Arrays.stream(cookies).limit(cookies.length);
            limit.forEach(cookie ->{
                cookieString.append(cookie.getName() + ":" +cookie.getValue());
            });
        }

        Object proceed = joinPoint.proceed();
        log.info("返回了");
        return proceed;
    }

}
